<!--新建文件夹、仪表板-->
<template>
    <el-card class="panel-index wly-page">
        <div style="display: flex;position: relative;height: 100%">
            <div style="position: relative;" :style="`width:${asideExpend?aside.w:0}px`"
                 :class="['aside',[asideExpend?'':'hideChild']]">
                <VueDraggableResizable :active="true" class-name="my-class" class-name-active="my-active-class"
                                       class-name-handle="my-handle-class" :minWidth="180" :w="250" :maxWidth="450"
                                       :draggable="false" :h="544" @resizing="onResize">
                    <div class="aside-box">
                        <div style="display: flex;justify-content: space-around">
                            <el-button type="text" size="mini" icon="el-icon-document-add"
                                       @click="addNewBoard(null,'file')">新建仪表盘
                            </el-button>
                            <el-button type="text" size="mini" icon="el-icon-folder-add"
                                       @click="addNewBoard(null,'folder')">新建文件夹
                            </el-button>
                        </div>
                        <div style="margin-top: 10px">
                            <el-input placeholder="搜索仪表板" v-model="searchPanel" size="mini" clearable
                                      @clear="handleClear"
                                      prefix-icon="el-icon-search">
                            </el-input>
                        </div>
                        <div class="tree-box">
                            <span style="cursor: pointer" @click="qryMenuData()"><i
                                class="el-icon-data-analysis"></i>全部文件</span>
                            <el-tree
                                ref="tree"
                                :data="menuData"
                                :props="defaultProps"
                                node-key="menuId"
                                :filter-node-method="filterNode"
                                :current-node-key="currentNodeKey"
                                accordion
                                @node-click="dataToBread">
                                <div slot-scope="{ node, data }" class="my-tree-node">
                                    <div class="title">
                                        <i :class="node.expanded?'el-icon-folder-opened':'el-icon-folder'"
                                           v-if="data.attr == '1'"></i>
                                        <i class="el-icon-odometer" v-else-if="data.attr == '2'"></i>
                                        <i class="el-icon-data-analysis" v-else-if="data.attr == '3'"></i>
                                        <span>{{data.name}}</span>
                                    </div>
                                    <div class="my-tree-node-action">
                                        <el-dropdown trigger="hover">
                                            <i class="el-icon-more" style="color: #F95160"></i>
                                            <el-dropdown-menu slot="dropdown">
                                                <template v-if="data.attr == '1'">
                                                    <el-dropdown-item icon="el-icon-edit"
                                                                      @click.native="addNewBoard(data,'folder')">新建文件夹
                                                    </el-dropdown-item>
                                                    <el-dropdown-item icon="el-icon-delete"
                                                                      @click.native="addNewBoard(data,'file')">新建仪表盘
                                                    </el-dropdown-item>
                                                </template>
                                                <el-dropdown-item icon="el-icon-edit-outline"
                                                                  @click.native="renamePanel(data)">重命名
                                                </el-dropdown-item>
                                                <el-dropdown-item icon="el-icon-delete"
                                                                  @click.native="deletePanel(data)">删除
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </div>
                                </div>
                            </el-tree>
                        </div>
                    </div>
                </VueDraggableResizable>
                <i slot="mr" :class="['expend',[asideExpend?'el-icon-arrow-left':'el-icon-arrow-right']]"
                   @click="asideExpend = !asideExpend"></i>
            </div>
            <div v-if="!asideExpend" class="aside-bar">
                <i slot="mr" :class="['expend','el-icon-arrow-right']" @click="asideExpend = !asideExpend"></i>
            </div>
            <div style="flex: 1;border-left: 1px solid #ccc;width: 0">
                <TemplateIndex ref="templateIndex" :boardId="curBoardId" :name="curBoardName" :is-edit="false"></TemplateIndex>
            </div>
        </div>
        <rename-dialog ref="renameDialog" @saved="qryMenuData()"></rename-dialog>
    </el-card>
</template>

<script>
    import { DASH_BORARD, QUERY_DASH_BORARD, QUERY_DASH_BORARD_TREE } from '@api/url'
import VueDraggableResizable from 'vue-draggable-resizable-gorkys'
import 'vue-draggable-resizable-gorkys/dist/VueDraggableResizable.css'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'
import ajax from '../../api/ajax'
import VHeader from '../../components/VHeader/VHeader'
import FileBreadcrumb from './scopeedcomponents/FileBreadcrumb'
import RenameDialog from './scopeedcomponents/RenameDialog'
import TemplateIndex from './templateConfig/TemplateIndex'

    export default {
        name: 'PanelIndex',
        components: {
            VHeader,
            RenameDialog,
            FileBreadcrumb,
            TemplateIndex,
            VueDraggableResizable
        },
        watch: {
            searchPanel(val) {
                this.$refs.tree.filter(val);
            }
        },
        data() {
            return {
                searchPanel: null,
                height: window.innerHeight - 230,
                treeFileName: [],
                menuData: [],
                currentRow: {
                    menuId: '0',
                    type: '6',
                    parentId: '0'
                }, // 当前目录的父级ID
                searchFlag: false,
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                aside: {
                    x: 0,
                    y: 0,
                    w: 250,
                    h: 600
                },
                asideExpend: true,
                curBoardId: null,
                curBoardName: '',
                currentNodeKey:''
            }
        },
        methods: {
            onResize: function (x, y, width, height) {
                this.aside = {
                    x,
                    y,
                    w: width,
                    height: height
                }
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.name.indexOf(value) !== -1;
            },
            /**
             * 新建仪表板
             * @param val 选中节点的数据
             * @param type 新建类型 file:文件 folder：文件夹
             */
            addNewBoard(val, type = 'file') {
                this.renamePanel({
                    attr:type === 'file'?'2':'1',
                    parentId:val?val.menuId:'0'
                })

                // this.$prompt('请输入名称', '提示', {
                //     inputValue: `新建${type === 'file' ? '仪表盘' : '文件夹'}`,
                //     confirmButtonText: '确定',
                //     cancelButtonText: '取消',
                // }).then(({value}) => {
                //     const parentId = val ? (val.menuId.toString() || '0') : '0'
                //     let param = {
                //         optMode: 'A',
                //         name: value,
                //         type: '6',
                //         attr: type === 'file' ? '2' : '1',
                //         parentId,
                //         mark: '1111'
                //     }
                //     ajax.post(DASH_BORARD, param).then(res => {
                //         this.qryMenuData()
                //     }).catch(err => {
                //         console.error('操作失败！', err)
                //     })
                // });

            },
            // 新建文件夹(这儿需要返回文件夹名)
            addNewFolders(val) {
                // 传入当前目录的父级id给后台
                let param = {
                    optMode: 'A',
                    name: '新建文件夹',
                    type: '6',
                    attr: '1',
                    parentId: val.menuId === '0' ? '0' : val.menuId,
                    mark: '1111'
                }
                ajax.post(DASH_BORARD, param).then(res => {
                    let param = {
                        menuId: val.menuId,
                        type: '6'
                    }
                    this.qryMenuData(param)
                }).catch(err => {
                    console.error('操作失败！', err)
                }).finally(() => {

                })
            },
            /**
             * 查询所有目录
             * @param val
             */
            qryMenuData(val) {
                this.currentRow = val
                const param = {type: '6'}
                if (val) {
                    param.menuId = val.menuId || '0'
                } else {
                    param.parentId = '0'
                    this.curBoardName = '全部'
                }
                ajax.post(QUERY_DASH_BORARD_TREE, param).then(res => {
                    const treeSort = (arr = []) => {
                        const sort = []
                        arr.forEach(item => {
                            if(item.attr === '1'){
                                sort.unshift({...item,children:treeSort(item.children||[])})
                            }else{
                                sort.push(item)
                            }
                        })
                        return sort;
                    }
                    this.menuData = treeSort(res.data)
                    if(this.curBoardId){
                        this.setDefaultKey(this.curBoardId)
                    }
                })
            },
            // 点击当前节点查询子节点数据且传递数据给面包屑
            dataToBread(val, node) {
                // 文件夹
                if (val.attr === '1') {
                    this.currentRow = val
                // 仪表盘
                } else if (val.attr === '2') {
                    this.$refs['templateIndex'].init()
                    sessionStorage.setItem('boardId', val.menuId)
                    sessionStorage.setItem('curBoard', JSON.stringify({id:val.menuId,name:val.name}))
                    this.curBoardId = val.menuId
                    this.curBoardName = val.name
                    this.$router.replace({
                        name: 'PanelIndex',
                        query: {
                            boardId: val.menuId,
                        }
                    })
                }else if(val.attr === '3'){
                    this.$router.push({
                        name: 'dataScreen',
                        query: {
                            boardId: val.menuId,
                        }
                    })
                }
            },
            // 重命名
            renamePanel(val) {
                this.$refs.renameDialog.openDialog(val)
            },
            // 删除
            deletePanel(val) {
                let param = {
                    optMode: 'D',
                    menuId: val.menuId
                }
                ajax.post(DASH_BORARD, param).then(res => {
                    this.$message.success('删除成功！')
                    this.qryMenuData()
                })
            },
            // 搜索仪表盘
            searchPanelData(val) {
                this.searchFlag = true
                let param = {
                    name: val,
                    treeFlag: false,
                    type: '6',
                    attr: '2'
                }
                ajax.post(QUERY_DASH_BORARD, param).then(res => {
                    this.menuData = res.data
                })
            },
            handleClear() {
                this.searchFlag = false
                let val = {
                    menuId: '0',
                    type: '6',
                    parentId: '0'
                }
                this.qryMenuData(val)
            },
            arrayToTree(items) {
                let res = [] // 存放结果集
                let map = {}
                // 判断对象是否有某个属性
                let getHasOwnProperty = (obj, property) => Object.prototype.hasOwnProperty.call(obj, property)

                // 边做map存储，边找对应关系
                for (const i of items) {
                    map[i.menuId] = {
                        ...i,
                        children: getHasOwnProperty(map, i.menuId) ? map[i.menuId].children : []
                    }
                    const newItem = map[i.menuId]
                    if (i.parentId == 0) {
                        if(newItem.attr === '1'){
                            res.unshift(newItem)
                        }else{
                            res.push(newItem)
                        }
                    } else {
                        if (!getHasOwnProperty(map, i.parentId)) {
                            map[i.parentId] = {
                                children: []
                            }
                        }
                        if(newItem.attr === '1'){
                            map[i.parentId].children.unshift(newItem)
                        }else{
                            map[i.parentId].children.push(newItem)
                        }
                    }
                }
                return res
            },
            setDefaultKey(key){
                this.currentNodeKey = key;
                this.$nextTick(() => {

                    this.$refs.tree.setCurrentKey(key)
                })
            }

        },
        created() {
            this.searchFlag = false
            this.qryMenuData()
        },
        mounted() {
            const curBoardId = this.$route.query.boardId
            if(curBoardId){
                this.curBoardId = curBoardId;
                if(this.menuData.length !==0){
                    this.setDefaultKey(this.curBoardId)
                }
            }
            const datas = [
                {
                    objType:1, // 对象类型 => 图表对象/装饰对象
                    location:{ // 位置数据
                        x:100, // 左上角x坐标
                        y:100,// 左上角y坐标
                        z:1,  // 层级，值越大越在上层
                        w:200, // 宽度
                        h:200, // 高度
                    },
                    tableOptions:{ // 图表对象配置
                        tableType:1, // 图表类型 => 饼图/折线图/...
                        dataSourceType:1, // 数据源类型 => 静态/动态
                        static:{ // 静态数据配置
                            // 按照echart渲染格式输出
                            // ...
                        },
                        dynamic:{ // 动态数据配置
                            url:'', // 接口
                            type:1, // 接口类型 http / websocket
                        }
                    },
                    otherOptions:{// 装饰对象配置
                        bgUrl:'', // 背景图地址
                        svgUrl:'',
                    }
                }
            ]
        }
    }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .panel-index /deep/ {
        height 100%
        .el-card__body{
            height 100% !important
        }
        .v-header {
            margin-bottom 0 !important

            p {
                margin 0 !important
            }
        }
    }

    .aside-bar {
        background white
    }

    .aside {
        position relative
        z-index 1000

        &.hideChild {
            overflow-x hidden
            z-index 10000
        }

        &:hover {
            .expend {
                opacity 1
            }
        }

        .expend {
            opacity 0
            position absolute
            z-index: 1000
            top 0
            right 0
            transform translateX(50%)
            background white
            width 20px
            height 20px
            border-radius 50%
            border 1px solid #F87071
            text-align center
            line-height 20px
            cursor pointer
            transition all 0.1s
            color #F87071

            &.el-icon-d-arrow-right {
                display block
                transform translateX(0)
            }

        }

        .aside-box {
            display flex
            flex-direction column
            margin 0 10px 0 0

            .tree-box {
                margin-top 10px
                flex-grow 1
                flex-basis 465px
                overflow-y auto

                .my-tree-node {
                    width 100%
                    display flex
                    justify-content space-between
                    align-items center
                    .title{
                        flex 1
                        width 0
                        overflow hidden
                        text-overflow ellipsis
                        word-break keep-all
                        white-space nowrap
                    }
                    .my-tree-node-action {
                        visibility hidden
                        padding 0 10px
                    }

                    &:hover {
                        .my-tree-node-action {
                            visibility visible

                            .el-icon-more {
                                transform rotate(90deg)
                            }
                        }
                    }
                }
            }
        }

    }

    .my-class /deep/, .my-active-class /deep/ {
        border none
        /*border-right: 1px solid #ccc;*/

        .my-handle-class {
            display none !important
        }

        .my-handle-class-mr {
            width 20px !important
            height 20px !important
            top: 50% !important;
            margin-top: -7px !important;
            right: 0 !important;
            cursor: e-resize !important;
            position: absolute;
            background-image: url('~@asst/image/dotted.png');
            background-size: 100% 100%;
            z-index: 1000;
            transform: translateX(50%);
            display block !important
        }
    }

    .panel-index
        .u-btn
            display none

        .table-head
            display inline-block
            width 100%
            padding 8px 16px
            background-color #F5F7FA
            border 1px solid #c0c4cc
            margin-bottom 10px

        .el-table tr:hover
            .u-btn
                display inline


</style>
